package com.baidu.reflect;

import com.baidu.annotation.MyTest;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;

public class D02_UserReflect {
    public static void main(String[] args) throws Exception {
        //创建一个实例对象
        User user = new User("袁峰", 30, 1000);
        Class<User> userClass = User.class;

        //=======================================1.获取构造器==========================================
        Constructor<User> constructor = userClass.getDeclaredConstructor(String.class, int.class);
        //1.2.打开权限
        constructor.setAccessible(true);
        //1.3.基于构造器获取对象实例
        User user1 = constructor.newInstance("袁峰", 30);
        System.out.println(user1);

        //=======================================2.获取属性==========================================
        //2.1.获取所有成员变量
        Field[] fields = userClass.getDeclaredFields();
        //2.2.创建map用于存储结果
        HashMap hashMap = new HashMap();

        //2.2.遍历
        for (Field field : fields) {
            //2.3.暴力破解权限
            field.setAccessible(true);
            String name = field.getName();
            Class<?> type = field.getType();
            //2.3.获取对象对应的属性值
            Object value = field.get(user);
            hashMap.put(name, value);
        }
        System.out.println(hashMap);

        //=======================================3.获取方法==========================================
        //3.1.获取所有方法
        Method[] methods = userClass.getDeclaredMethods();
        for (Method method : methods) {
            //3.2.暴力破解权限
            method.setAccessible(true);

            //3.3.获取返回值类型
            Class<?> returnType = method.getReturnType();
            System.out.println(method.getName() + "方法的返回值类型" + returnType);

            Class<?>[] parameterTypes = method.getParameterTypes();
            System.out.println(method.getName() + "方法的参数类型" + Arrays.toString(parameterTypes));

        }

        //3.2.获取指定方法
        Method delete = userClass.getDeclaredMethod("delete", int.class, String.class);
        //3.3.组织参数
        Object[] funArgs = {9999999, "男生"};
        //3.4.执行方法
        Object invoke = delete.invoke(user, funArgs);
        //Object invoke = delete.invoke(user, 9999999, "男生");
        System.out.println(invoke);

        //=======================================4.获取注解==========================================
        Method[] methods2 = userClass.getDeclaredMethods();
        for (Method method : methods2) {
            MyTest annotation = method.getAnnotation(MyTest.class);
            if (null != annotation){
                System.out.println(method.getName() + "方法的注解是" + annotation.annotationType());
            }
        }
    }
}
